<template>
    <div>
      <!--    面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><b>题目管理</b></el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/FindTest' }">题库</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #545c99">创建题目</span></el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-row>
          <el-link href="#/MyTestInfo">
            查看我创建的所有题目<i class="el-icon-view el-icon--right"></i>
          </el-link>
        </el-row>
        <br>
        <el-steps :active="active" finish-status="success">
          <el-step title="创建题目" icon="el-icon-plus"></el-step>
          <el-step title="编辑内容" icon="el-icon-edit"></el-step>
          <el-step title="上传附件" icon="el-icon-upload"></el-step>
        </el-steps>
        <br>
        <el-row :gutter="20">
          <el-col :span="10">
            <span style="color: gray"><i class="el-icon-user"></i> 当前创建题目者: <el-tag> {{this.AddTestForm.author}}</el-tag></span>
          </el-col>
          <el-col :span="12">
            <span style="color: gray"><i class="el-icon-s-order"></i> 该教师工号：<el-tag type="info"> {{this.AddTestForm.teacher}}</el-tag></span>
          </el-col>
        </el-row>
        <br>
        <div v-if="this.IsCreate">
          <el-divider content-position="right"><i class="el-icon-plus"></i></el-divider>
          <br>
          <el-form status-icon label-width="150px" :model="AddTestForm" ref="AddTestFormRef">
          <el-form-item label="题目名字" prop="name" required>
            <el-input v-model="AddTestForm.name" autocomplete="off" placeholder="请输入题目名字"></el-input>
          </el-form-item>
          <el-form-item label="题目类型" prop="type" required>
            <el-select v-model="AddTestForm.type" placeholder="请选择题目类型">
              <el-option label="单选题" value="select"></el-option>
              <el-option label="多选题" value="muti"></el-option>
              <el-option label="填空题" value="fill"></el-option>
              <el-option label="简答题" value="essay"></el-option>
              <el-option label="实验题" value="experience"></el-option>
              <el-option label="判断题" value="judge"></el-option>
            </el-select>
          </el-form-item>
<!--          填空题-->
          <el-form-item label="填空题答案(选填)" v-show="AddTestForm.type === 'fill' ? true : false">
            <el-input v-model="AddTestForm.fillAnswer" placeholder="请输入该填空题答案(选填)"></el-input>
          </el-form-item>
          <!--        本题总分-->
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'fill' ? true : false">
            <el-input-number v-model="grade2" label="本题总分"></el-input-number>
          </el-form-item>
<!--          选择题-->
          <el-collapse v-model="activeNames"  v-show="AddTestForm.type === 'select' ? true : false">
            <el-collapse-item name="1">
              <template slot="title">
                <span style="color: cornflowerblue">编辑单选题选项内容 </span><i class="header-icon el-icon-info"></i>
              </template>
              <el-form-item label="A选项题目(选填)">
                <el-input v-model="AddTestForm.selectA" placeholder="请输入A选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="B选项题目(选填)">
                <el-input v-model="AddTestForm.selectB" placeholder="请输入B选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="C选项题目(选填)">
                <el-input v-model="AddTestForm.selectC" placeholder="请输入C选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="D选项题目(选填)">
                <el-input v-model="AddTestForm.selectD" placeholder="请输入D选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          <el-form-item label="单选题答案(选填)" v-show="AddTestForm.type === 'select' ? true : false">
            <el-select v-model="AddTestForm.selectAnswer" placeholder="请输入该单选题答案（选填）">
              <el-option label="选项A" value="A"></el-option>
              <el-option label="选项B" value="B"></el-option>
              <el-option label="选项C" value="C"></el-option>
              <el-option label="选项D" value="D"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'select' ? true : false">
            <el-input-number v-model="grade2" :min="0" label="本题总分"></el-input-number>
          </el-form-item>
<!--          多选题-->
          <el-collapse v-model="activeNames"  v-show="AddTestForm.type === 'muti' ? true : false">
            <el-collapse-item name="1">
              <template slot="title">
                <span style="color: cornflowerblue">编辑多选题选项内容 </span><i class="header-icon el-icon-info"></i>
              </template>
              <el-form-item label="A选项题目(选填)">
                <el-input v-model="AddTestForm.selectA" placeholder="请输入A选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="B选项题目(选填)">
                <el-input v-model="AddTestForm.selectB" placeholder="请输入B选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="C选项题目(选填)">
                <el-input v-model="AddTestForm.selectC" placeholder="请输入C选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="D选项题目(选填)">
                <el-input v-model="AddTestForm.selectD" placeholder="请输入D选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          <el-form-item label="多选题答案(选填)" v-show="AddTestForm.type === 'muti' ? true : false ">
            <template>
              <el-checkbox-group v-model="checkedChoice" @change="handleCheckedChoiceChange">
                <el-checkbox v-for="select in choice" :value="select" :label="select" :key="select">{{select}}</el-checkbox>
              </el-checkbox-group>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            </template>
          </el-form-item>
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'muti' ? true : false">
            <el-input-number v-model="grade3" :min="0" label="本题总分"></el-input-number>
          </el-form-item>
<!--          判断题-->
          <el-collapse v-model="activeNames"  v-show="AddTestForm.type === 'judge' ? true : false">
            <el-collapse-item name="1">
              <template slot="title">
                <span style="color: cornflowerblue">编辑判断题选项内容 </span><i class="header-icon el-icon-info"></i>
              </template>
              <el-form-item label="判断正确选项(选填)">
                <el-input v-model="AddTestForm.judgeTrue" placeholder="请输入正确选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
              <el-form-item label="判断错误选项(选填)">
                <el-input v-model="AddTestForm.judgeFalse" placeholder="请输入错误选项内容" suffix-icon="el-icon-edit"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          <el-form-item label="判断题答案(选填)" v-show="AddTestForm.type === 'judge' ? true : false ">
            <el-row>
              <el-col :span="6">
                <el-switch
                  :disabled="jinyong"
                  v-model="panduan"
                  active-text="正确"
                  inactive-text="错误">
                </el-switch>
              </el-col>
              <el-col :span="6">
                <el-tag @click="JinYong">
                  {{this.tishi}}<i :class="tubiao"></i>
                </el-tag>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'judge' ? true : false">
            <el-input-number v-model="grade1" :min="0" label="本题总分"></el-input-number>
          </el-form-item>
<!--          简答题-->
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'essay' ? true : false">
            <el-input-number v-model="grade4" :min="0" label="本题总分"></el-input-number>
          </el-form-item>
<!--          实验题-->
          <el-form-item label="本题总分" required v-show="AddTestForm.type === 'experience' ? true : false">
            <el-input-number v-model="grade5" :min="0" label="本题总分"></el-input-number>
          </el-form-item>
        </el-form>
        </div>
          <br>
        <br>
        <el-row :gutter="20">
          <el-col :offset="10">
            <el-button class="new_btn" icon="el-icon-plus" @click="CreateTest">创 建</el-button>
          </el-col>
        </el-row>
        <!--        文本编辑器-->
        <div v-if="this.IsEdit">
          <el-divider content-position="right"><i class="el-icon-share"></i>编辑内容</el-divider>
          <br>
          <template>
            <div>
              <mavon-editor
                class="editor"
                :ishljs="true"
                :toolbars="markdownOption"
                ref=md @imgAdd="$imgAdd" v-model="mdStr" @imgDel="$imgDel"></mavon-editor>
            </div>
          </template>
          <br><br>
          <el-row :gutter="20">
  <!--          <el-col :offset="10">-->
  <!--            <el-button type="primary" icon="el-icon-edit" @click="UpdateImg">创 建</el-button>-->
  <!--          </el-col>-->
            <el-col :span="5" :offset="5">
              <el-button class="white_btn" @click="JumpEdit">跳过编辑</el-button>
            </el-col>
            <el-col :span="5" :offset="5">
              <el-button class="new_btn" icon="el-icon-edit" @click="EditContent">确定编辑</el-button>
            </el-col>
          </el-row>
        </div>
<!--        上传附件-->
        <div v-if="this.IsUpload">
          <el-divider content-position="right"><i class="el-icon-upload"></i>上传附件</el-divider>
          <br>
          <el-row>
            <el-col :span="18" :offset="1">
              <el-upload
                class=""
                ref="upload"
                action="doUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :limit="1"
                :before-upload="beforeUpload">
                <el-button slot="trigger" class="white_btn">
                  <i class="el-icon-plus"></i>选取文件
                </el-button>
                <div slot="tip" class="el-upload__tip">附件请单个依次上传，且每次上传不得超过5MB。（文档格式为doc或docx，视频文件格式为MP4）</div>
                <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
              </el-upload>
            </el-col>
            <el-col :offset="1" :span="4">
              <el-button class="new_btn" @click="submitUpload()">
                <i class="el-icon-upload"></i>确定上传
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-card>

    </div>
</template>

<script>
import axios from 'axios'
const choiceOptions = ['A', 'B', 'C', 'D']

export default {
  name: 'AddTest',
  data () {
    return {
      // 编辑器功能
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      AddTestForm: {
        name: '',
        type: '',
        author: localStorage.getItem('name'),
        teacher: localStorage.getItem('username'),
        fillAnswer: '',
        selectA: '',
        selectB: '',
        selectC: '',
        selectD: '',
        selectAnswer: '',
        mutiAnswer: '', // this.checkedChoice.join()
        judgeTrue: '',
        judgeFalse: '',
        judgeAnswer: '', // panduan
        totalScore: ''
      },
      checkAll: false,
      checkedChoice: [],
      choice: choiceOptions,
      isIndeterminate: true,
      panduan: true,
      jinyong: false,
      grade1: 1, // judge
      grade2: 2, // select,fill
      grade3: 4, // muti
      grade4: 10, // essay
      grade5: 30, // experience
      tubiao: 'el-icon-error',
      tishi: '禁用',
      activeNames: [''],
      active: 0,
      img_file: {},
      mdStr: '',
      IsCreate: true, // 判断是否创建题目界面 true
      TestId: '', // 创建题目ID
      IsEdit: false, // 判断是否编辑题目内容界面 false
      IsUpload : false, // 判断是否是上传附件界面 false
      //  上传
      fileList: [],
      fileName: '',
      files: [],
      type:''
    }
  },
  created () {
  },
  methods: {
    handleCheckAllChange (val) {
      this.checkedChoice = val ? choiceOptions : []
      this.isIndeterminate = false
    },
    handleCheckedChoiceChange (value) {
      var checkedCount = value.length
      this.checkAll = checkedCount === this.choice.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.choice.length
    },
    CreateTest () {
      var type = this.AddTestForm.type
      if (type === 'select' || type === 'fill') {
        this.AddTestForm.totalScore = this.grade2
      } else if (type === 'muti') {
        this.AddTestForm.totalScore = this.grade3
        if (this.checkedChoice) {
          this.AddTestForm.mutiAnswer = this.checkedChoice.join('')
          console.log(this.AddTestForm.mutiAnswer)
          console.log(this.AddTestForm.selectA)
        }
      } else if (type === 'essay') {
        this.AddTestForm.totalScore = this.grade4
      } else if (type === 'experience') {
        this.AddTestForm.totalScore = this.grade5
      } else if (type === 'judge') {
        this.AddTestForm.totalScore = this.grade1
        if (!this.jinyong) {
          if (this.panduan) {
            this.AddTestForm.judgeAnswer = 'true'
          } else {
            this.AddTestForm.judgeAnswer = 'false'
          }
        }
      }
      console.log(this.AddTestForm.totalScore)
      console.log(this.AddTestForm)
      this.$refs.AddTestFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 调用接口进行用户添加
        axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
        const { data: res } = await this.$http.post('/test/create/', this.AddTestForm)
        if (res.status !== 200) {
          console.log(res)
          return this.$message.error('创建题目失败！')
        }
        this.$message.success('创建题目成功!')
        this.active = 1
        // 接受创建的题目ID
        this.TestId = res.data.testId
        // 切换操作界面
        this.IsEdit = true
        this.IsCreate = false
        console.log(res.data)
        console.log(this.AddTestForm)
      })
    },
    JinYong () {
      this.jinyong = !this.jinyong
      this.tubiao = 'el-icon-success'
      this.tishi = '选用'
    },
    $imgAdd (pos, $file) {
      // 缓存图片信息
      this.img_file[pos] = $file
      console.log($file)
    },
    $imgDel (pos) {
      delete this.img_file[pos]
    },
    UpdateImg () {
      axios.defaults.headers.post['Content-Type'] = false
      // 第一步.将图片上传到服务器.
      const formdata = new FormData()
      for (var _img in this.img_file) {
        formdata.append('file', this.img_file[_img])
        formdata.append('content', '')
        formdata.append('name', 'image')
        formdata.append('typeId', 'image')
        formdata.append('testId', '')
        formdata.append('homeworkId', '')
      }
      console.log(formdata.name)
      console.log(this.img_file)
      axios({
        url: '/file/uploadImage',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'charset=UTF-8; multipart/form-data', Origin1: 'http://218.244.149.226' }
      }).then((res) => {
        console.log(this)
        if (this.status !== 200) {
          this.$message.error = '上传失败!'
        }
        this.$message.success = '上传成功！'
        const resData = res.data.data
        /**
         * 例如：返回数据为 res = [[pos, url], [pos, url]...]
         * pos 为原图片标志（0）
         * url 为上传后图片的url地址
         */
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        // for (var img in res) {
        //   this.$refs.md.$img2Url(img.pos, img.url)
        // }
        if (resData) {
          for (var img in resData.length) {
            this.$refs.md.$img2Url(img, resData[img].image)
            console.log(img, resData[img].image)
          }
        }
      })
    },
  //  跳过编辑
    JumpEdit(){
      // this.IsEdit = false
      this.IsUpload = true
    },
  //  编辑题目内容
    async EditContent (){
      console.log(this.mdStr)
      const confirmResult = await this.$confirm('该操作将上传题目内容，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消上传')
      }
      const file = new Blob()
      const formdata = new FormData()
      formdata.append('file', file)
      formdata.append('content', this.mdStr)
      formdata.append('name', 'content')
      formdata.append('typeId', 'md')
      formdata.append('testId', this.TestId) // this.testId
      formdata.append('homeworkId', '')
      console.log(formdata)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      }
      const { data: res } = await this.$http.post('/file/uploadFile/', formdata, config)
      if (res.status !== 200) {
        return this.$message.error(res.msg + '编辑内容失败！')
      }
      this.$message.success('编辑内容成功！')
      // 切换操作界面
      this.active = 2
      this.IsEdit = false
      this.IsUpload = true
    },
  //  上传文件
    beforeUpload(file){
      if (!file){
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      // debugger
      console.log(file,'文件');
      this.files = file
      const extension = file.name.split('.')[1]
      const isLt2M = file.size / 1024 / 1024 < 5
      if (extension != 'docx' && extension != 'doc' && extension != 'mp4') {
        this.$message.warning('上传附件格式出错')
        return
      }
      if (!isLt2M) {
        this.$message.warning('上传大小不能超过 5MB!')
        return
      }
      this.fileName = file.name;
      if (extension === 'doc' || extension === 'docx'){
        this.type = 'docx'
      }
      else if (extension === 'mp4') {
        this.type = 'mp4'
      }
      return false // 返回false不会自动上传
    },
    uploadFile(file){
      this.fileslist.append('file', file.file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    async submitUpload() {
      const confirmResult = await this.$confirm('确定上传该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消上传')
      }
      this.$refs.upload.submit();
      // debugger
      // console.log('上传'+this.files.name)
      let type = this.type
      if (type) {
        console.log(this.files, type)
        const formdata = new FormData();
        formdata.append('file', this.files)//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
        formdata.append('content', '')
        formdata.append('name', type)
        formdata.append('typeId', type)
        formdata.append('testId', this.TestId)
        formdata.append('homeworkId', '')
        console.log(formdata)
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
        }
        const { data: res } = await this.$http.post('/file/uploadFile/', formdata, config)
        if (res.status !== 200) {
          return this.$message.error(res.msg)
        }
        this.active = 3
        this.$message.success('上传附件成功！')
        // 刷新
        setTimeout(() =>{
          this.$router.go(0)
        },2000);
      }
    },
  }
}
</script>

<style scoped>
  .editor{
    min-height: 600px;
    width: 90%;
    text-align: center;
    margin: auto;
  }
</style>
